package cqrtplm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hustcad.plm.basic.entity.TyplmObjectAliasDO;
import com.hustcad.plm.basic.service.TyplmObjectAliasService;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.basic.util.TyplmLoggerUtil;
import com.hustcad.plm.basic.util.TyplmPinYinUtil;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.folder.service.TyplmCabinetService;
import com.hustcad.plm.pdm.user.mapper.TyplmMemberLinkMapper;
import com.hustcad.plm.pdm.user.model.dto.OrgExtParamDTO;
import com.hustcad.plm.pdm.user.model.dto.PdmUserDTO;
import com.hustcad.plm.pdm.user.model.dto.PrincipalMemberDTO;
import com.hustcad.plm.pdm.user.model.entity.PdmUser;
import com.hustcad.plm.pdm.user.model.vo.OrgExtVO;
import com.hustcad.plm.pdm.user.service.*;
import com.hustcad.plm.pdm.user.service.organization.PdmUserService;
import com.hustcad.plm.pdm.user.util.TyplmUserDealUtil;
import com.lark.oapi.okhttp.OkHttpClient;
import com.lark.oapi.okhttp.Request;
import com.lark.oapi.okhttp.Response;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.PrincipalEntity;
import com.ty.basic.entity.org.MemberLinkDO;
import com.ty.basic.entity.org.OrgContainerDO;
import com.ty.basic.entity.org.OrgDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.handler.exceptionhandler.exception.ResponseCodeEnum;
import com.ty.basic.handler.exceptionhandler.exception.TyException;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.dto.OrderChangeDTO;
import cqrtplm.dto.RTDeptDTO;
import cqrtplm.entity.DeptRoleDO;
import cqrtplm.entity.WorkflowMapping;
import cqrtplm.mapper.DeptRoleMapper;
import cqrtplm.service.OrderChangeService;
import cqrtplm.service.RTOaIntegrityService;
import cqrtplm.service.RTOrgService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RTOaIntegrityServiceImpl implements RTOaIntegrityService {

    @Value("${oa.token.url:http://222.179.153.58:82/seeyon/rest/token/oaapi/3ad5b59f-3508-40d4-a2b1-dcc8043671ee}")
    private String oaTokenUrl;
    @Value("${oa.getToken.url}")
    private String oaGetTokenUrl;
    @Value("${rato.process_url}")
    private String processUrl;
    @Value("${rato.rest_name}")
    private String restName;
    @Value("${rato.rest_password}")
    private String restPassword;
    private String currentLoginName;
    @Value("${oa.department.url:http://222.179.153.58:82/seeyon/rest/orgDepartments/}")
    private String oaDepartmentUrl;
    @Value("${oa.member.url:http://222.179.153.58:82/seeyon/rest/orgMembers/}")
    private String oaUserUrl;
    @Value("${oa.account.id:3ad5b59f-3508-40d4-a2b1-dcc8043671ee}")
    private String accountId;
    @Value("${oa.deptRole.url: http://192.168.102.1:7003/OASystem/OaApi/GetOADPTRoleList?dptname=&rolename=}")
    private String oaDeptRoleUrl;
    @Value("${typlm.org.Name: \\u6da6\\u901a\\u4e8b\\u4e1a\\u90e8}")
    private String rtplmOrgName;
    @Resource
    private DeptRoleMapper deptRoleMapper;
    @Resource
    private TyplmOrgService typlmOrgService;
    @Resource
    private TyplmOrgContainerService typlmOrgContainerService;
    @Resource
    private TyOrgExtService tyOrgExtService;
    @Resource
    private TyplmMemberLinkService typlmMemberLinkService;
    @Resource
    private TyplmUserService typlmUserService;
    @Resource
    private TyplmPrincipalService typlmPrincipalService;
    @Resource
    private TyplmCabinetService typlmCabinetService;
    @Resource
    private TyplmObjectAliasService typlmObjectAliasService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private PdmUserService pdmUserService;
    @Resource
    private RTOrgService rtOrgService;
    @Resource
    private TyplmMemberLinkMapper typlmMemberLinkMapper;
    @Resource
    private OrderChangeService orderChangeService;
    @Resource
    WorkflowMappingServiceImpl workflowMappingService;

    /**
     * @author dinglonghao
     * @date 2025/11/11$ 下午8:09$
     * 不同场景下构建下发OA数据 true构建表头与订单表格数据 false 构建变更物料数据
     */
    public Map<String, Object> buildRequestBody(BigInteger oid, Boolean flag) {
        OrderChangeDTO data = orderChangeService.getByOid(oid.toString());
         if (ObjectUtils.isEmpty(data)) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("appName", "collaboration");

        Map<String, Object> data1 = new HashMap<>();
        data1.put("templateCode", "T_DSPF_ZTBG_01");
        data1.put("draft", "0");

        Map<String, Object> data2 = new HashMap<>();

        // 构建表单主数据（通用部分）
        Map<String, Object> formMainData = buildFormMainData(data);
        data2.put("formmain_15220", formMainData);

        if (flag) {
            // 构建订单明细数据
            buildOrderDetailData(data, data2);
        } else {
            // 构建物料变更数据
            buildMaterialChangeData(data, data2);
        }

        data1.put("data", data2);
        map.put("data", data1);

        return map;
    }

    /**
     * 构建表单主数据
     */
    private Map<String, Object> buildFormMainData(OrderChangeDTO data) {
        Map<String, Object> formMainData = new HashMap<>();

        formMainData.put("field0048", data.getHeader().getCustomerName()); // CUSTOMER_NAME
        formMainData.put("field0028", data.getHeader().getRequirementNumber()); // REQUIREMENT_NUMBER
        formMainData.put("field0030", data.getHeader().getStatusChangeNumber()); // STATUS_CHANGE_NUMBER
        formMainData.put("field0031", data.getHeader().getProposalDate()); // PROPOSAL_DATE

        // 终端生产工厂
        String terminalFactoryValue = getFactoryValue(data.getHeader().getPowerFactory());
        formMainData.put("field0033", terminalFactoryValue); // TERMINAL_FACTORY

        // 动力生产工厂
        String powerFactoryValue = getFactoryValue(data.getHeader().getPowerFactory());
        formMainData.put("field0034", powerFactoryValue); // POWER_FACTORY

        formMainData.put("field0032", data.getHeader().getNewStatusPublishTime()); // NEW_STATUS_PUBLISH_TIME
        formMainData.put("field0057", "-5997255816051931349"); // CHANGE_CATEGORY
        formMainData.put("field0059", data.getHeader().getProductCode()); // PRODUCT_CODE
        formMainData.put("field0060", data.getHeader().getModel()); // MODEL
        formMainData.put("field0007", data.getHeader().getIsOpeProduct()); // IS_OPE_PRODUCT
        formMainData.put("field0042", "-2908085026470147178"); // 发起方式

        return formMainData;
    }

    /**
     * 获取工厂对应的值
     */
    private String getFactoryValue(String factoryName) {
        if (factoryName.contains("重庆")) {
            return "7297002888947912700";
        } else if (factoryName.contains("越南")) {
            return "2262936808011875364";
        } else {
            return "-3003594118196344863";
        }
    }

    /**
     * 构建订单明细数据
     */
    private void buildOrderDetailData(OrderChangeDTO data, Map<String, Object> data2) {
        List<Map<String, Object>> detailList = new ArrayList<>();

        data.getDetails().forEach(item -> {
            Map<String, Object> detail = new HashMap<>();
            detail.put("field0017", item.getOrderNumber()); // ORDER_NUMBER
            detail.put("field0018", item.getItemSequence()); // ITEM_SEQUENCE
            detail.put("field0019", item.getOriginalPlanDate()); // ORIGINAL_PLAN_DATE

            // 是否影响交期
            String affectDeliveryValue = item.getAffectDelivery().contains("是")
                    ? "-7048306469799574892" : "-6091180120647513895";
            detail.put("field0020", affectDeliveryValue); // AFFECT_DELIVERY

            // 在制成品处置
            String workInProcessValue = item.getWorkInProcess().contains("是")
                    ? "-7048306469799574892" : "-6091180120647513895";
            detail.put("field0052", workInProcessValue); // WORK_IN_PROCESS

            // 库存成品处置
            String finishedInventoryValue = item.getFinishedInventory().contains("是")
                    ? "-7048306469799574892" : "-6091180120647513895";
            detail.put("field0053", finishedInventoryValue); // FINISHED_INVENTORY

            // 零部件处置
            String partComponentValue = item.getPartComponent().contains("是")
                    ? "-7048306469799574892" : "-6091180120647513895";
            detail.put("field0054", partComponentValue); // PART_COMPONENT

            detailList.add(detail);
        });

        data2.put("formson_15224", detailList);
    }

    /**
     * 构建物料变更数据
     */
    private void buildMaterialChangeData(OrderChangeDTO data, Map<String, Object> data2) {
        List<Map<String, Object>> materialList = new ArrayList<>();

        data.getMaterials().forEach(item -> {
            Map<String, Object> material = new HashMap<>();
            material.put("field0027", item.getBeforeMaterial()); // 变更前
            material.put("field0029", item.getAfterMaterial()); // 变更后
            material.put("field0050", item.getProductCode()); // 变更项目
            material.put("field0056", item.getDevRemark()); // 成本确认

            materialList.add(material);
        });

        data2.put("formson_15228", materialList);
    }


    @Override
    public String getOAToken(String loginName) {
        this.currentLoginName = loginName;
        String url = String.format(oaGetTokenUrl + "/rest/token/%s/%s?loginName=%s", restName,
                                   restPassword, loginName);
        System.out.println(url);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            assert response.body() != null;
            String body = response.body().string();
            System.out.println(body);
            JSONObject jsonObject = JSONObject.parseObject(body);
            return jsonObject.getString("id");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * @return $RETURN$
     * @author dinglonghao
     * @date 2025/11/11$ 下午11:13$
     * 发起OA流程 如果是非状态更改 更新数据库状态!
     */
    public String startProcess(String token, Map<String, Object> formData, BigInteger workFlowContainerId,
                               Boolean flag) {
        // 构建请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        // 构建请求体
        String jsonData = JSON.toJSONString(formData, SerializerFeature.WriteBigDecimalAsPlain);
        String url = String.format(processUrl + "?token=%s", token);
        try {
            // 使用 Hutool 发送 POST 请求启动流程
            String response = HttpUtil.createPost(url)
                    .addHeaders(headers)
                    .body(jsonData)
                    .execute()
                    .body();
            JSONObject jsonObject = JSONObject.parseObject(response);
            if (!"0".equals(jsonObject.get("code").toString())) {
                new RuntimeException(jsonObject.getString("message"));
            } else {
                WorkflowMapping workflowMapping = new WorkflowMapping();
                workflowMapping.setWorkFlowContainerId(workFlowContainerId.toString());
                workflowMapping.setOaProcessOid(jsonObject.getJSONObject("data").getJSONObject("app_bussiness_data").getString("summaryId"));
                if (flag) {
                    workflowMapping.setStatus("订单信息已发至OA");
                    workflowMappingService.create(workflowMapping);
                } else {
                    workflowMapping.setStatus("物料信息已发至OA");
                    workflowMappingService.update(workFlowContainerId.toString(), workflowMapping);
                }
            }
            return response;
        } catch (Exception e) {
            log.error("流程启动失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getOaToken() {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(oaTokenUrl)
                .method("GET", null)
                .addHeader("Content-Type", "application/json")
                .addHeader("Cookie", "JSESSIONID=C1E23D9957B62C4752F849414632F2CF")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(body);
            return jsonObject.getString("id");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void synOrganizationalStructure() {
        String oaToken = getOaToken();
        JSONArray allUser = getAllUser(oaToken);
        List<RTDeptDTO> allDept = getAllDept(oaToken);
        OrgExtVO orgRoot = this.tyOrgExtService.getOrgRoot();
        OrgExtParamDTO ratoOrgDTO = new OrgExtParamDTO();
        ratoOrgDTO.setOid(orgRoot.getOid());
        ratoOrgDTO.setOtype(orgRoot.getOtype());
        List<OrgExtVO> memberOrgsByOrg = this.tyOrgExtService.getMemberOrgsByOrg(ratoOrgDTO);
        List<OrgExtVO> ratoOrg = memberOrgsByOrg.stream().filter(orgExtVO -> orgExtVO.getName().equals(rtplmOrgName))
                .collect(Collectors.toList());
        OrgExtVO ratoOrgExtVO = ratoOrg.get(0);
        BigInteger ratoOrgOid = ratoOrgExtVO.getOid();
        createDepartment(allDept, ratoOrgOid);
        for (Object o : allUser) {
            JSONObject user = (JSONObject) o;
            try {
                PdmUserDTO pdmUserDTO = new PdmUserDTO();
                pdmUserDTO.setAccount(user.getString("code").trim());
                pdmUserDTO.setUsername(user.getString("name"));
                pdmUserDTO.setContaineroid(ratoOrgExtVO.getOrgContainerOid());
                pdmUserDTO.setContainerotype(TableTypeConstrant.TY_ORGCONTAINER_OTYPE);
                String orgDepartmentId = user.getString("orgDepartmentId");
                if (orgDepartmentId.startsWith("-")) {
                    orgDepartmentId = orgDepartmentId.replaceFirst("-", "");
                }
                pdmUserDTO.setOrgOid(new BigInteger(orgDepartmentId));
                pdmUserDTO.setEmail(user.getString("emailAddress"));
                if ("1".equals(user.getString("gender"))) {
                    pdmUserDTO.setSex("male");
                } else {
                    pdmUserDTO.setSex("female");
                }
                pdmUserDTO.setTele(user.getString("telNumber"));
                pdmUserDTO.setStatus("1");
                String userId = user.getString("id");
                if (userId.startsWith("-")) {
                    userId = userId.replaceFirst("-", "");
                }
                PdmUser pdmUser = pdmUserService.getUserByOid(new BigInteger(userId));
                if (ObjectUtils.isEmpty(pdmUser)) {
                    try {
                        createUserInOrg(pdmUserDTO, new BigInteger(userId));
                    } catch (Exception e) {
                        log.error("更新人员信息失败:{}", pdmUserDTO);
                    }
                } else {
                    //更新人员信息
                    pdmUser.setEmail(user.getString("emailAddress"));
                    pdmUser.setName(user.getString("code"));
                    pdmUser.setTelephone(user.getString("telNumber"));
                    pdmUser.setDisabled(0L);
                    String sex = user.getString("gender").equals("1") ? "male" : "female";
                    pdmUser.setExt1(sex);
                    pdmUserService.updateuser(pdmUser);
                    //更新人员部门
                    Example example = new Example(MemberLinkDO.class);
                    example.createCriteria().andIn("boid", ListUtil.toList(pdmUser.getOid())).andIn("botype",
                                                                                                    ListUtil.toList(
                                                                                                            TableTypeConstrant.TY_USER_OTYPE))
                            .andIn("aotype", ListUtil.toList(TableTypeConstrant.TY_ORG_OTYPE));
                    List<MemberLinkDO> memberLinkDOS = typlmMemberLinkMapper.selectByExample(example);
                    //组织不变
                    String orgDepartmentId2 = user.getString("orgDepartmentId");
                    if (orgDepartmentId2.startsWith("-")) {
                        orgDepartmentId2 = orgDepartmentId2.replaceFirst("-", "");
                    }
                    String finalOrgDepartmentId = orgDepartmentId2;
                    if (memberLinkDOS.stream().anyMatch(f -> f.getAoid().toString().equals(finalOrgDepartmentId))) {
                        continue;
                    }
                    OrgDO orgByName = typlmOrgService.getOrgByName(user.getString("orgAccountName"));
                    if (ObjectUtil.isNotEmpty(orgByName)) {
                        for (MemberLinkDO memberLinkDO : memberLinkDOS) {
                            if (memberLinkDO.getAoid().equals(orgByName.getOid())) {
                                continue;
                            }
                            //构建组织
                            IdentifierEntity orgIdentifierEntity = new IdentifierEntity();
                            orgIdentifierEntity.setOtype(memberLinkDO.getAotype());
                            orgIdentifierEntity.setOid(memberLinkDO.getAoid());
                            //构建用户
                            IdentifierEntity userIdentifierEntity = new IdentifierEntity();
                            userIdentifierEntity.setOtype(pdmUser.getOtype());
                            userIdentifierEntity.setOid(pdmUser.getOid());
                            PrincipalMemberDTO principalMemberDTO = new PrincipalMemberDTO();
                            principalMemberDTO.setEntity(orgIdentifierEntity);
                            principalMemberDTO.setRelatentity(ListUtil.toList(userIdentifierEntity));
                            typlmMemberLinkService.removeEntityBaseFromGroup(principalMemberDTO);
                        }
                        //构建组织
                        IdentifierEntity orgIdentifierEntity = new IdentifierEntity();
                        orgIdentifierEntity.setOtype(TableTypeConstrant.TY_ORG_OTYPE);
                        orgIdentifierEntity.setOid(new BigInteger(finalOrgDepartmentId));
                        //构建用户
                        IdentifierEntity userIdentifierEntity = new IdentifierEntity();
                        userIdentifierEntity.setOtype(pdmUser.getOtype());
                        userIdentifierEntity.setOid(pdmUser.getOid());
                        PrincipalMemberDTO principalMemberDTO = new PrincipalMemberDTO();
                        principalMemberDTO.setEntity(orgIdentifierEntity);
                        principalMemberDTO.setRelatentity(ListUtil.toList(userIdentifierEntity));
                        typlmMemberLinkService.addEntityBaseToGroup(principalMemberDTO);
                    }
                }
            } catch (Exception e) {
                log.info("用户同步失败:{}", user);
                throw new RuntimeException(e);
            }
        }

    }

    public void createDepartment(List<RTDeptDTO> allDept, BigInteger ratoOrgOid) {

        for (RTDeptDTO dto : allDept) {

            OrgExtParamDTO paramDTO = new OrgExtParamDTO();
            paramDTO.setParentOtype(TableTypeConstrant.TY_ORG_OTYPE);
            paramDTO.setName(dto.getDeptName());
            String superior = dto.getSuperior();
            if (superior.equals(accountId)) {
                paramDTO.setParentOid(ratoOrgOid);
            } else {
                if (superior.startsWith("-")) {
                    superior = superior.replaceFirst("-", "");
                    paramDTO.setParentOid(new BigInteger(superior));
                } else {
                    paramDTO.setParentOid(new BigInteger(superior));
                }
            }
            String deptId = dto.getDeptId();
            if (deptId.startsWith("-")) {
                deptId = deptId.replaceFirst("-", "");
            }

            try {
                OrgDO orgDO = typlmOrgService.queryOrgById(new BigInteger(deptId));
                if (ObjectUtils.isEmpty(orgDO)) {
                    //新增
                    rtOrgService.createDepartment(paramDTO, new BigInteger(deptId));
                } else {
                    //更新逻辑
                    OrgExtParamDTO orgExtParamDTO = new OrgExtParamDTO();
                    BeanUtils.copyProperties(orgDO, orgExtParamDTO);
                    orgExtParamDTO.setName(paramDTO.getName());
                    orgExtParamDTO.setParentOid(paramDTO.getParentOid());
                    tyOrgExtService.updateOrganization(orgExtParamDTO);
                    log.info("部门已存在:{}", orgDO);
                }
            } catch (Exception e) {
                log.info("paramDTO=========>:{},deptID=========>{}", paramDTO, deptId);
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            List<RTDeptDTO> childDept = dto.getChildDept();
            if (CollUtil.isNotEmpty(childDept)) {
                createDepartment(childDept, ratoOrgOid);
            }
        }
    }

    public void createUserInOrg(PdmUserDTO user, BigInteger userOid) {
        TyplmEntityBaseUtil.checkParamNotNull(user.getOrgOid(), "orgOid");
        TyplmLoggerUtil.debug(log, () -> "createUserInOrg的入参PdmUserDTO为==>【{}】",
                              () -> new Object[]{JSON.toJSONString(user)});
        OrgDO org = this.typlmOrgService.queryOrgById(user.getOrgOid());
        if (org == null) {
            throw new TyException(Collections.singletonList(new TyException(ResponseCodeEnum.BIZ_OBJECT_NOT_FOUND,
                                                                            new String[]{TyplmEntityBaseUtil.getOtypeDisplayName(
                                                                                    "ty.inteplm.org.CTyOrg") + ":" + user.getOrgOid()})));
        } else {
            try {
                this.createUserInOrg(org, this.getOrgContainerByOrg(org), user, userOid);
            } catch (Exception e) {
                log.error("创建用户失败user :{}", user);
                log.error("创建用户失败:{}", e.getMessage());
                throw new RuntimeException(e);
            }
        }
    }

    private void createUserInOrg(OrgDO org, OrgContainerDO containerDO, PdmUserDTO user, BigInteger userOid) {
        TyplmEntityBaseUtil.checkParamNotNull(org, "Org");
        TyplmEntityBaseUtil.checkParamNotNull(containerDO, "OrgContainer");
        TyplmUserDealUtil.checkName(user.getAccount());
        TyplmUserDealUtil.checkFullName(user.getUsername());
        if (StringUtils.isNotBlank(user.getPassword())) {
            user.setPassword(SecureUtil.sha256(user.getPassword()));
        }

        if (StringUtils.isBlank(user.getLang())) {
            user.setLang("zh_CN");
        }

        user.setStatus("1");
        if (this.typlmUserService.checkName(null, user.getAccount().trim())) {
            log.error("用户已经存在:{}", user.getAccount());
        } else {
            user.setOid(userOid.toString());
            user.setOtype("ty.inteplm.org.CTyUser");
            PdmUser pdmUser = TyplmUserDealUtil.coverUserToDo(user);
            this.setDefaultFields(user, pdmUser);
            pdmUser.setDomainoid(containerDO.getDomainoid());
            pdmUser.setDomainotype(containerDO.getDomainotype());
            pdmUser.setContaineroid(containerDO.getOid());
            pdmUser.setContainerotype(containerDO.getOtype());
            this.typlmPrincipalService.checkPrincipal(pdmUser);
            List<TyplmObjectAliasDO> pinYinDOList = new ArrayList<>();
            String fullnamePinyin;
            List<TyplmObjectAliasDO> fullNamepinYinDOList;
            if (Strings.isNotBlank(pdmUser.getName())) {
                fullnamePinyin = TyplmPinYinUtil.getPinyinByChinese(pdmUser.getName());
                pdmUser.setNamepinyin(fullnamePinyin);
                fullNamepinYinDOList = this.typlmObjectAliasService.batchDealTyplmPinYinDO(userOid,
                                                                                           "ty.inteplm.org.CTyUser",
                                                                                           "ty_user;name",
                                                                                           fullnamePinyin);
                if (CollUtil.isNotEmpty(fullNamepinYinDOList)) {
                    pinYinDOList.addAll(fullNamepinYinDOList);
                }
            }

            if (Strings.isNotBlank(pdmUser.getFullname())) {
                fullnamePinyin = TyplmPinYinUtil.getPinyinByChinese(pdmUser.getFullname());
                pdmUser.setFullnamepinyin(fullnamePinyin);
                fullNamepinYinDOList = this.typlmObjectAliasService.batchDealTyplmPinYinDO(userOid,
                                                                                           "ty.inteplm.org.CTyUser",
                                                                                           "ty_user;fullname",
                                                                                           fullnamePinyin);
                if (CollUtil.isNotEmpty(fullNamepinYinDOList)) {
                    pinYinDOList.addAll(fullNamepinYinDOList);
                }
            }

            user = this.coverUserToDto(pdmUserService.createuserByDO(pdmUser), new PdmUserDTO());
            if (CollUtil.isNotEmpty(pinYinDOList)) {
                this.typlmObjectAliasService.batchInsertPinyin(pinYinDOList);
            }

            UserDO userDO = this.typlmUserService.queryUserByKey(pdmUser.getOid());
            this.typlmCabinetService.createPersonalCabinetAndSubfolder(Collections.singletonList(userDO));
            if (org.getOid().equals(containerDO.getOrgoid())) {
                this.typlmMemberLinkService.addParentForPrincipal(Collections.singletonList(org), userDO);
            } else {
                OrgDO containerOrg = this.typlmOrgService.queryOrgByKey(containerDO.getOrgoid());
                List<OrgDO> list = new ArrayList<>(Arrays.asList(org, containerOrg));
                this.typlmMemberLinkService.addParentForPrincipal(list, userDO);
            }

            if (TyAccountContext.isDebug()) {
                log.info("createUserInOrg的出参user为<==【{}】", JSON.toJSONString(user));
            }

        }
    }

    public PdmUserDTO coverUserToDto(PdmUser pdmUser, PdmUserDTO pdmUserDTO) {
        BeanUtil.copyProperties(pdmUser, pdmUserDTO);
        BigInteger bid = pdmUser.getOid();
        String btype = pdmUser.getOtype();
        PrincipalEntity principalEntity = new PrincipalEntity(bid, btype);
        List<PrincipalEntity> outParent = this.typlmPrincipalService.getOneOutParentOrg(principalEntity);
        if (CollUtil.isNotEmpty(outParent)) {
            String orgIds = outParent.stream().map(CTyEntityBaseDO::getOid).map(BigInteger::toString).collect(
                    Collectors.joining(","));
            String orgNames = outParent.stream().map(CTyEntityBaseDO::getName).collect(Collectors.joining(","));
            pdmUserDTO.setOrganizationId(orgIds);
            pdmUserDTO.setOrganizationDisplay(orgNames);
        } else {
            pdmUserDTO.setOrganizationId(null);
            pdmUserDTO.setOrganizationDisplay(null);
        }

        pdmUserDTO.setDesc(pdmUser.getDescription());
        if (pdmUser.getDisabled() == 0L) {
            pdmUserDTO.setStatus("1");
        }

        if (pdmUser.getDisabled() == 1L) {
            pdmUserDTO.setStatus("0");
        }

        pdmUserDTO.setSex(pdmUser.getExt1());
        pdmUserDTO.setBirthday(pdmUser.getExt2());
        pdmUserDTO.setPhoto(pdmUser.getExt3());
        pdmUserDTO.setUsername(pdmUser.getFullname());
        pdmUserDTO.setAccount(pdmUser.getName());
        pdmUserDTO.setOid(pdmUser.getOid() == null ? null : pdmUser.getOid().toString());
        pdmUserDTO.setTele(pdmUser.getTelephone());
        pdmUserDTO.setCreatestamp(pdmUser.getCreatestamp());
        pdmUserDTO.setUpdatestamp(pdmUser.getUpdatestamp());
        pdmUserDTO.setPassword(null);
        if (!TyplmEntityBaseUtil.isEmptyOid(pdmUser.getContaineroid())) {
            CTyEntityBaseDO container = CommonUtil.getEntity(
                    new IdentifierEntity(pdmUser.getContaineroid(), pdmUser.getContainerotype()));
            pdmUserDTO.setContaineroid(pdmUser.getContaineroid());
            pdmUserDTO.setContainerotype(pdmUser.getContainerotype());
            pdmUserDTO.setContextName(container.getName());
        }

        pdmUserDTO.setLang(pdmUser.getLang());
        TyplmLoggerUtil.debug(log, () -> "coverUserToDto的出参pdmUserDTO为<==【{}】",
                              () -> new Object[]{JSON.toJSONString(pdmUserDTO)});
        return pdmUserDTO;
    }

    private void setDefaultFields(PdmUserDTO user, PdmUser pdmUser) {
        if (null == user.getTele() || "".equals(user.getTele())) {
            pdmUser.setTelephone(null);
        }

        if (null == user.getBirthday() || "".equals(user.getBirthday())) {
            pdmUser.setExt2(null);
        }

        if (null == user.getEmail() || "".equals(user.getEmail())) {
            pdmUser.setEmail(null);
        }

        if (StringUtils.isNotBlank(pdmUser.getPassword())) {
            pdmUser.setPassword(this.passwordEncoder.encode(pdmUser.getPassword()));
        }

    }

    private OrgContainerDO getOrgContainerByOrg(OrgDO org) {
        OrgContainerDO containerDO = null;
        if ("ty.inteplm.domain.CTySiteContainer".equals(org.getContainerotype())) {
            containerDO = this.typlmOrgContainerService.queryOrgContainerByOrg(org.getOid(), org.getOtype());
        } else {
            containerDO = this.typlmOrgContainerService.queryOrgContainerByOid(org.getContaineroid());
        }

        if (containerDO == null) {
            throw new TyException(Collections.singletonList(
                    new TyException(ResponseCodeEnum.BIZ_OBJECT_NOT_FOUND, new String[]{"OrgContainer"})));
        } else {
            if (TyAccountContext.isDebug()) {
                log.info("getOrgContainerByOrg的出参containerDO为<==【{}】", JSON.toJSONString(containerDO));
            }

            return containerDO;
        }
    }

    private List<RTDeptDTO> getAllDept(String oaToken) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        String url = oaDepartmentUrl + accountId + "?token=" + oaToken;
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("Authorization", "284d3cea-1cd8-460c-ac54-7fdd5f62c070")
                .addHeader("Cookie", "JSESSIONID=C1E23D9957B62C4752F849414632F2CF")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            JSONArray array = JSONObject.parseArray(body);
            return RTDeptDTO.convert(array, accountId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private JSONArray getAllUser(String oaToken) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        String url = oaUserUrl + accountId + "?token=" + oaToken;
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("Cookie", "JSESSIONID=C1E23D9957B62C4752F849414632F2CF")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            return JSONObject.parseArray(body);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void getOADeptRoleList() {
        Map<String, DeptRoleDO> newMap = getDeptRoleDOMap();
        List<DeptRoleDO> deptRoleDOS = deptRoleMapper.selectAll();
        Map<String, DeptRoleDO> oldMap = Optional.ofNullable(deptRoleDOS).orElse(Collections.emptyList()).stream()
                .collect(Collectors.toMap(
                        DeptRoleDO::getOid,
                        o -> o,
                        (existing, replacement) -> existing
                ));

        List<DeptRoleDO> toUpdate = new ArrayList<>();
        List<DeptRoleDO> toInsert = new ArrayList<>();
        List<DeptRoleDO> toDelete = new ArrayList<>();

        // 分类处理
        newMap.forEach((key, value) -> {
            if (oldMap.containsKey(key)) {
                DeptRoleDO old = oldMap.get(key);
                // 判断是否需要更新（字段值变化）
                if (!value.equals(old)) {
                    DeptRoleDO.fillCommonFieldForUpdate(old, new Date());
                    toUpdate.add(old);
                }
            } else {
                DeptRoleDO.fillCommonFieldForCreate(value, new Date());
                toInsert.add(value);
            }
        });

        oldMap.forEach((key, value) -> {
            if (!newMap.containsKey(key)) {
                toDelete.add(value);
            }
        });

        if (CollUtil.isNotEmpty(toUpdate)) {
            toUpdate.forEach(deptRoleMapper::updateByPrimaryKey);
        }

        if (CollUtil.isNotEmpty(toInsert)) {
            toInsert.forEach(deptRoleMapper::insert);
        }

        if (CollUtil.isNotEmpty(toDelete)) {
            toDelete.forEach(deptRoleMapper::delete);
        }
    }

    private Map<String, DeptRoleDO> getDeptRoleDOMap() {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Request request = new Request.Builder()
                .url(oaDeptRoleUrl)
                .method("GET", null)
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(body);
            JSONArray data = jsonObject.getJSONArray("data");
            return DeptRoleDO.convertToDeptRoleDOMap(data);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
